using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace Agricultural_Sales.ASP
{
    public partial class Home : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCategories();
                LoadProducts();
            }
        }

        private void LoadCategories()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string sql = "SELECT CategoryId, CategoryName FROM ProductCategory ORDER BY CategoryName";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    try
                    {
                        conn.Open();
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                ListItem item = new ListItem(
                                    reader["CategoryName"].ToString(),
                                    reader["CategoryId"].ToString()
                                );
                                ddlCategory.Items.Add(item);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // 错误处理
                        Response.Write("<script>alert('加载分类失败：" + ex.Message + "');</script>");
                    }
                }
            }
        }

        private void LoadProducts(int categoryId = 0, string searchText = "")
        {
            string connectionString = ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string sql = @"SELECT p.ProductId, p.Name, p.Origin, p.Price, p.Inventory, p.Unit, p.Descr,
                              CASE 
                                  WHEN p.ImageUrl IS NULL OR p.ImageUrl = '' THEN '~/Image/default-product.png'
                                  WHEN p.ImageUrl LIKE '/images/%' THEN REPLACE(p.ImageUrl, '/images/', '~/Image/')
                                  ELSE p.ImageUrl
                              END AS ImageUrl,
                              pc.CategoryName
                              FROM Product p 
                              LEFT JOIN ProductCategory pc ON p.CategoryId = pc.CategoryId
                              WHERE p.Inventory > 0";

                // 添加分类筛选条件
                if (categoryId > 0)
                {
                    sql += " AND p.CategoryId = @CategoryId";
                }

                // 添加商品名称搜索条件
                if (!string.IsNullOrEmpty(searchText))
                {
                    sql += " AND (p.Name LIKE @SearchText OR p.Origin LIKE @SearchText OR p.Descr LIKE @SearchText)";
                }

                sql += " ORDER BY p.ProductId DESC";

                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    if (categoryId > 0)
                    {
                        cmd.Parameters.AddWithValue("@CategoryId", categoryId);
                    }

                    if (!string.IsNullOrEmpty(searchText))
                    {
                        cmd.Parameters.AddWithValue("@SearchText", "%" + searchText + "%");
                    }

                    try
                    {
                        conn.Open();
                        using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                        {
                            DataTable dt = new DataTable();
                            adapter.Fill(dt);

                            if (dt.Rows.Count > 0)
                            {
                                rptProducts.DataSource = dt;
                                rptProducts.DataBind();
                                rptProducts.Visible = true;
                                pnlNoProducts.Visible = false;
                            }
                            else
                            {
                                rptProducts.Visible = false;
                                pnlNoProducts.Visible = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // 错误处理
                        Response.Write("<script>alert('加载商品失败：" + ex.Message + "');</script>");
                        rptProducts.Visible = false;
                        pnlNoProducts.Visible = true;
                    }
                }
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            int categoryId = Convert.ToInt32(ddlCategory.SelectedValue);
            string searchText = txtSearch.Text.Trim();
            LoadProducts(categoryId, searchText);
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            ddlCategory.SelectedIndex = 0;
            txtSearch.Text = "";
            LoadProducts();
        }

        protected string GetImageUrl(object imageUrl)
        {
            if (imageUrl == null || string.IsNullOrEmpty(imageUrl.ToString()))
            {
                return "~/Image/default-product.png";
            }

            string url = imageUrl.ToString();
            if (url.StartsWith("/images/"))
            {
                return url.Replace("/images/", "~/Image/");
            }

            return url;
        }
    }
}